package org.eenie.appseed.ui.crash

import android.content.Intent
import android.text.TextUtils
import android.view.MenuItem
import androidx.appcompat.view.menu.ActionMenuItemView
import androidx.core.content.FileProvider
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.FileIOUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.eenie.appseed.BuildConfig
import org.eenie.appseed.databinding.ActivityLogPreviewBinding
import org.eenie.core.base.viewbinding.BaseBindingActivity
import org.eenie.core.view.bar.NavMenuClickListener
import java.io.File

class LogPreviewActivity : BaseBindingActivity<ActivityLogPreviewBinding>(), NavMenuClickListener {

    private var logPath = ""


    override fun initUI() {


        this.binding.appBar.setMenuClickListener(this)



        logPath = intent.getStringExtra("path") ?: ""
        if (!TextUtils.isEmpty(logPath)) {

            lifecycleScope.launch {
                val code = withContext(Dispatchers.IO) {
                    val data = FileIOUtils.readFile2String(logPath)
                    return@withContext data
                }
                this@LogPreviewActivity.binding.tvCode.text = code
            }


        }

    }

    override fun onMenuClick(item: MenuItem, view: ActionMenuItemView) {
        val file = File(logPath)
        val uri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".provider", file)
        val shareIntent = Intent(Intent.ACTION_SEND)
        shareIntent.type = "application/octet-stream"
        // intent.type = "image/jpeg"
        shareIntent.putExtra(Intent.EXTRA_STREAM, uri)
        startActivity(shareIntent)
    }

    override fun providerBinding() = ActivityLogPreviewBinding.inflate(layoutInflater)
}